package net.sf.microlog.midp.bluetooth.server;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.microlog.midp.bluetooth.BluetoothServerListener;

/**
 * Keeps track of all connected clients.
 * 
 * @author Jarle Hansen (hansjar@gmail.com)
 * 
 */
public enum BluetoothConnectionsUtil {
	;

	private static final Map<Integer, BluetoothStreamReaderThread> connectionMap = new ConcurrentHashMap<Integer, BluetoothStreamReaderThread>();
	private static int threadCounter = 0;

	private static boolean shutdown = false;

	/**
	 * Removes a connection from the connectionList.
	 * 
	 * @param connectionId
	 */
	static void removeConnection(final int connectionId) {
		connectionMap.remove(connectionId);
	}

	/**
	 * Adds a connection to the connectionList.
	 * 
	 * @param bluetoothConnection
	 */
	static synchronized void addConnection(
			final BluetoothStreamReaderThread bluetoothConnection) {
		if (!shutdown) {
			final int connectionId = threadCounter++;
			connectionMap.put(connectionId, bluetoothConnection);
			bluetoothConnection.setConnectionId(connectionId);
		}
	}

	/**
	 * When the [STOP] command is sent, the server will gracefully shut down.
	 * This means it will loop through the connectionList and shut down all
	 * active connections before taking down the Bluetooth server.
	 * 
	 * @param bluetoothServerListener
	 */
	static synchronized void gracefulShutdown(
			final BluetoothServerListener bluetoothServerListener) {
		if (!shutdown) {
			shutdown = true;
			
			Collection<BluetoothStreamReaderThread> connectionMapValues = connectionMap
					.values();
			for (BluetoothStreamReaderThread bluetoothStreamReaderThread : connectionMapValues) {
				bluetoothStreamReaderThread.closeConnection();
			}

			if (bluetoothServerListener != null) {
				bluetoothServerListener.shutdown();
			}

			System.out.println("Number of open connections at shutdown: "
					+ connectionMap.size());
		}
	}
}
